﻿using System;
using System.IO;
using System.Security.Cryptography;

namespace MyFunction.Encryption
{
    /// <summary>
    /// 加密标准 ( DES) 算法的加密及解密
    /// 参考：http://www.cnblogs.com/yiki/archive/2007/08/28/872373.html
    /// </summary>
	class MyEncryption
	{
        private string KEY_64 = "";//注意了，是8个字符，64位
        private string IV_64 = "";
        /// <summary>
        ///  初化加密
        /// </summary>
        /// <param name="keyvalue64">8个字符的 key </param>
        /// <param name="ivvlaue64">8个字符的 IV 值</param>
        public MyEncryption ( string keyvalue64 , string ivvlaue64 )
        {
            KEY_64 = keyvalue64;
            IV_64 = ivvlaue64;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Encode ( string data )
        {
           if ( string.IsNullOrEmpty(data))
           {
               return null;
           }
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes (KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes (IV_64);
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider ( );
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream ( );
            CryptoStream cst = new CryptoStream (ms , cryptoProvider.CreateEncryptor (byKey ,byIV) , CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter (cst);
            sw.Write (data);
            sw.Flush ( );
            cst.FlushFinalBlock ( );
            sw.Flush ( );
            return Convert.ToBase64String (ms.GetBuffer ( ) , 0 , (int)ms.Length);

        }
        /// <summary>
        ///  解密
        /// </summary>
        /// <param name="data">解密字串</param>
        /// <returns>返回解密之后的字串</returns>
        public string Decode ( string data )
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes (KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes (IV_64);

            if ( string.IsNullOrEmpty (data) )
            {
                return null;
            }
            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String (data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider ( );
            MemoryStream ms = new MemoryStream (byEnc);
            CryptoStream cst = new CryptoStream (ms , cryptoProvider.CreateDecryptor (byKey , byIV) , CryptoStreamMode.Read);
            try
            {
                
                StreamReader sr = new StreamReader (cst);
                return sr.ReadToEnd ( );
            }
            catch ( Exception )
            {
                return null;    
            }
        }
 
	}
}
